#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.

from esr_parser.parsers import world_pc, pc, world_mobile, mobile, detail
import json
from selenium.webdriver import PhantomJS
import uuid
from django.core.cache import cache
from datetime import datetime
import time

def get_driver():
    return PhantomJS()


def get_world_pc_ranking(keyword, order_by='general', tm_only=False, limit=100):
    if isinstance(keyword, str):
        keyword = keyword.decode('utf-8')

    driver = get_driver()

    try:
        task = world_pc.Rank_Task(
            driver, keyword, order_by=order_by, tm_only=tm_only, limit=limit)
        result_items, result_right_items, result_bottom_items = task.process()
    except Exception as e:
        raise e
    finally:
        print 'close task'
        driver.close()
        driver.quit()

    items_content = ""
    for item in result_items:
        items_content += json.dumps(item, ensure_ascii=False)
        items_content += "\n"

    right_items_content = ""
    for item in result_right_items:
        right_items_content += json.dumps(item, ensure_ascii=False)
        right_items_content += "\n"

    bottom_items_content = ""
    for item in result_bottom_items:
        bottom_items_content += json.dumps(item, ensure_ascii=False)
        bottom_items_content += "\n"

    return {"items": items_content, "right_items": right_items_content, "bottom_items": bottom_items_content}


def get_pc_ranking(keyword, order_by='general', tm_only=False, limit=604):
    if isinstance(keyword, str):
        keyword = keyword.decode('utf-8')

    driver = get_driver()
    print 'start task'
    try:
        task = pc.Rank_Task(driver, keyword, order_by=order_by,
                            tm_only=tm_only, limit=limit)
        result_items, result_right_items, result_bottom_items = task.process()
    except Exception as e:
        raise e
    finally:
        print 'close task'
        driver.close()
        driver.quit()

    items_content = ""
    for item in result_items:
        items_content += json.dumps(item, ensure_ascii=False)
        items_content += "\n"

    right_items_content = ""
    for item in result_right_items:
        right_items_content += json.dumps(item, ensure_ascii=False)
        right_items_content += "\n"

    bottom_items_content = ""
    for item in result_bottom_items:
        bottom_items_content += json.dumps(item, ensure_ascii=False)
        bottom_items_content += "\n"

    return {"items": items_content, "right_items": right_items_content, "bottom_items": bottom_items_content}


def get_world_mobile_ranking(keyword, order_by='general', tm_only=False, limit=50):
    if isinstance(keyword, str):
        keyword = keyword.decode('utf-8')
    print 'start task'

    driver = get_driver()
    try:
        task = world_mobile.Rank_Task(
            driver, keyword, order_by=order_by, tm_only=tm_only, limit=limit)
        result_items = task.process()
    except Exception as e:
        raise e
    finally:
        print 'close task'
        driver.close()
        driver.quit()

    items_content = ""
    for item in result_items:
        items_content += json.dumps(item)
        items_content += "\n"

    return {"items": items_content}


def get_mobile_ranking(keyword, order_by='general', tm_only=False, limit=200):
    if isinstance(keyword, str):
        keyword = keyword.decode('utf-8')

    driver = get_driver()
    print 'start task'
    try:
        task = mobile.Rank_Task(
            driver, keyword, order_by=order_by, tm_only=tm_only, limit=limit)
        result_items = task.process()
    except Exception as e:
        raise e
    finally:
        print 'close task'
        driver.close()
        driver.quit()

    items_content = ""
    for item in result_items:
        items_content += json.dumps(item)
        items_content += "\n"

    return {"items": items_content}


def item_detail(item_id, tmall, comment_limit=200):
    detail_data = detail.download(item_id, tmall, comment_limit)
    return detail_data


UU_SESSION=None
def get_cookies(use_cache=True):
    return {}
    now = datetime.now()
    global UU_SESSION
    if not UU_SESSION:
        UU_SESSION = str(uuid.uuid4())
    cookie_name = 'cookie_{}_{:%Y_%m_%d}'.format(UU_SESSION, now)
    cookies = cache.get(cookie_name)
    if cookies and use_cache:
        return cookies
    try:
        driver = get_driver()
        driver.get('https://www.taobao.com')
        driver.execute_script("$('[data-nation=CN]').click()")
        time.sleep(5)
        driver_cookies = driver.get_cookies()
        cookies = dict([(driver_cookie['name'], driver_cookie['value']) for driver_cookie in driver_cookies])
        cache.set(cookie_name, cookies, 600)
        return cookies
    except:
        pass
    finally:
        driver.close()
        driver.quit()


